from datetime import datetime
from app import db, login_manager
from flask_login import UserMixin
from werkzeug.security import generate_password_hash, check_password_hash
from sqlalchemy.orm import relationship

class User(db.Model, UserMixin):
    __tablename__ = 'tb_user'
    __table_args__ = {'extend_existing': True}
    
    user_id = db.Column(db.BigInteger, primary_key=True, autoincrement=True, comment='用户ID(主键)')
    username = db.Column(db.String(50), unique=True, nullable=False, comment='用户名')
    password = db.Column(db.String(255), nullable=False, comment='密码哈希值')
    phone = db.Column(db.String(20), comment='手机号')
    email = db.Column(db.String(100), comment='电子邮箱')
    icon = db.Column(db.String(255), comment='头像URL')
    mq_points = db.Column(db.Integer, default=0, comment='妙趣积分')
    saved_amount = db.Column(db.Numeric(10, 2), default=0.00, comment='累计节省金额(元)')
    reduced_waste = db.Column(db.Numeric(10, 2), default=0.00, comment='减少浪费量(kg)')
    badge_count = db.Column(db.Integer, default=0, comment='徽章数量')
    voucher_count = db.Column(db.Integer, default=0, comment='优惠券数量')
    create_time = db.Column(db.DateTime, default=datetime.now, comment='创建时间')
    last_login = db.Column(db.DateTime, comment='最后登录时间')
    is_admin = db.Column(db.Boolean, default=False, comment='是否为管理员(0-否,1-是)')
    
    # 定义关系 - 使用back_populates而不是backref
    orders = db.relationship('Order', back_populates='user', lazy='dynamic')
    behaviors = relationship("UserBehavior", back_populates="user", foreign_keys="UserBehavior.user_id")
    reviews = relationship("Review", back_populates="user", lazy='dynamic')
    addresses = relationship("Address", back_populates="user", lazy='dynamic', cascade='all, delete-orphan')
    
    # 尝试导入可能存在的其他关系
    try:
        point_records = relationship("PointRecord", back_populates="user", lazy='dynamic', cascade='all, delete-orphan')
    except:
        pass
    
    # Flask-Login支持
    def get_id(self):
        return str(self.user_id)
    
    # 密码处理
    def set_password(self, password):
        self.password = generate_password_hash(password)
        
    def check_password(self, password):
        # 兼容旧密码方式
        if password == self.password:
            return True
        return check_password_hash(self.password, password)
    
    def to_dict(self):
        """转换为字典，用于API响应"""
        return {
            'user_id': self.user_id,
            'username': self.username,
            'phone': self.phone,
            'email': self.email,
            'mq_points': self.mq_points,
            'saved_amount': float(self.saved_amount) if self.saved_amount else 0.00,
            'reduced_waste': float(self.reduced_waste) if self.reduced_waste else 0.00,
            'create_time': self.create_time.strftime('%Y-%m-%d %H:%M:%S') if self.create_time else None,
            'last_login': self.last_login.strftime('%Y-%m-%d %H:%M:%S') if self.last_login else None,
            'is_admin': self.is_admin
        }
    
    def __repr__(self):
        return f'<User {self.username}>'

@login_manager.user_loader
def load_user(user_id):
    """加载用户的回调函数"""
    return User.query.get(int(user_id)) 